<template>
  <el-select
    ref="selectTree"
    v-model="value"
    :placeholder="placeholder"
    style="width:100%"
    :disabled="disabled"
  >
    <el-option :value="values" hidden />
    <el-tree
      ref="treeOption"
      highlight-current
      accordion
      :node-key="defaultProps.value"
      :data="options"
      :props="defaultProps"
      :expand-on-click-node="false"
      @check="checkNode"
      @node-click="checkNode"
    />
  </el-select>
</template>

<script>
export default {
  name: 'TreeSelect',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: () => {
        return undefined
      }
    },
    placeholder: {
      type: String,
      default: () => {
        return '请选择'
      }
    },
    // 节点数据
    options: {
      type: Array, // 必须是树形结构的对象数组
      default: () => {
        return []
      }
    },
    // 设置label value属性
    defaultProps: {
      type: Object,
      default: () => {
        return {
          parentValue: 'parentValue', // 上级字段value值，用于给多选时默认展开defaultExpandedKeys
          value: 'value', // ID字段名
          label: 'label', // 显示名称
          children: 'children' // 子级字段名
        }
      }
    },
    // 默认勾选的节点
    defaultCheckNodes: {
      type: Array, // 已经分配的资源
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      values: {}
    }
  },
  methods: {
    // 勾选节点，
    checkNode(node) {
      this.values = node
      this.$refs.selectTree.blur()
      this.$emit('input', node.id, node[this.defaultProps.label])
    }
  }
}
</script>
